package com.cskaoyan.shopping.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        request.requestCheck();

        CartListByIdResponse response = new CartListByIdResponse();
        Map<String, String> map = redissonClient.getMap(request.getUserId().toString());

        List<CartProductDto> list = new ArrayList<>();
        for (String productId : map.keySet()) {
            String jsonStr = map.get(productId);
            CartProductDto cartProductDto = JSON.parseObject(jsonStr, CartProductDto.class);
            list.add(cartProductDto);
        }

        response.setCartProductDtos(list);

        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        request.requestCheck();

        AddCartResponse response = new AddCartResponse();
        Long userId = request.getUserId();
        Long productId = request.getItemId();
        Map<String, String> map = redissonClient.getMap(userId.toString());

        String jsonStr = map.get(request.getItemId());
        CartProductDto cartProductDto = null;
        if (StringUtils.isEmpty(jsonStr)) {
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            cartProductDto = CartItemConverter.item2Dto(item);
            cartProductDto.setProductNum(request.getNum().longValue());
            cartProductDto.setChecked("true");

        } else {
            cartProductDto = JSON.parseObject(jsonStr, CartProductDto.class);
            Long productNum = cartProductDto.getProductNum();
            long num = request.getNum().longValue();
            cartProductDto.setProductNum(productNum + num);
        }

        String newStr = JSON.toJSONString(cartProductDto);
        map.put(productId.toString(), newStr);

        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {

        request.requestCheck();
        Long userId = request.getUserId();
        Long productId = request.getItemId();
        Integer num = request.getNum();
        String checked = request.getChecked();

        Map<String, String> map = redissonClient.getMap(userId.toString());
        String jsonStr = map.get(productId.toString());

        CartProductDto cartProductDto = JSON.parseObject(jsonStr, CartProductDto.class);
        cartProductDto.setProductNum(num.longValue());
        cartProductDto.setChecked(checked);

        String newStr = JSON.toJSONString(cartProductDto);
        map.put(productId.toString(), newStr);

        return new UpdateCartNumResponse();
    }


    /**
     * @Description 全选购物车：将redis中该用户id对相应的hash数据中的value中所有对象的checked
     * 改为所传的数值
     * @Param [request]
     * @Return com.cskaoyan.shopping.dto.CheckAllItemResponse
     * @Author Lizhanpeng
     * @Date 2022/5/20
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse checkAllItemResponse = new CheckAllItemResponse();

        try {
            request.requestCheck();
            Long userId = request.getUserId();
            String checked = request.getChecked();
            RMap<String, String> map = redissonClient.getMap(String.valueOf(userId));
            //遍历其中数据并修改
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                CartProductDto cartProductDto = JSON.parseObject(entry.getValue(), CartProductDto.class);
                cartProductDto.setChecked(checked);
                String jsonString = JSON.toJSONString(cartProductDto);
                map.put(entry.getKey(), jsonString);
            }
            checkAllItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            checkAllItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(checkAllItemResponse, e);
        }
        return checkAllItemResponse;
    }

    /**
     * @Description 删除购物车中的商品，传入的为用户id与商品id 获取后从redis中删除即可
     * @Param [request]
     * @Return com.cskaoyan.shopping.dto.DeleteCartItemResponse
     * @Author Lizhanpeng
     * @Date 2022/5/20
     */
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();

        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            RMap<String, String> map = redissonClient.getMap(userId.toString());
            map.remove(itemId.toString());
            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteCartItemResponse, e);
        }

        return deleteCartItemResponse;
    }
/**
 * @Description 删除选中的数据
 * @Param [request]
 * @Return com.cskaoyan.shopping.dto.DeleteCheckedItemResposne
 * @Author Lizhanpeng
 * @Date 2022/5/20
 */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();
            Long userId = request.getUserId();
            RMap<String, String> map = redissonClient.getMap(userId.toString());
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            //遍历并删除checked为true的数据
            while (iterator.hasNext()){
                Map.Entry<String, String> entry = iterator.next();
                if (JSON.parseObject(entry.getValue(),CartProductDto.class).getChecked().equals("true")){
                    map.remove(entry.getKey());
                }
            }
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        ExceptionProcessorUtils.wrapperHandlerException(deleteCheckedItemResposne,e);
        }

        return deleteCheckedItemResposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
